package com.link_with_health.controller;

import com.alibaba.fastjson.JSONObject;
import com.link_with_health.common.Page;
import com.link_with_health.common.Result;
import com.link_with_health.common.TokenMap;
import com.link_with_health.model.AdminLogEntity;
import com.link_with_health.model.BatchModel;
import com.link_with_health.model.PatientEntity;
import com.link_with_health.service.AdminLogService;
import com.link_with_health.service.BatchOperationService;
import com.link_with_health.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

@Controller
@RequestMapping("/api/adminLog")
public class AminLogController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    public final String AUTH_TOKEN = "Authorization";

    private TokenMap tokenMap = TokenMap.getInstance();

    @Resource(name = "adminLogService")
    AdminLogService service;

    @Resource(name = "batchOperationService")
    BatchOperationService batchOperationService;

    /**
     * 查找日志信息
     * @param json json{method : '', params: {} }
     * @param request 请求
     * @return 返回查询结果
     */
    @PostMapping("/findAdminLogInfo")
    @ResponseBody
    public Result findAdminLogInfo(@RequestBody JSONObject json, HttpServletRequest request){
        String token = request.getHeader(AUTH_TOKEN);
        String msg = "验签验证失败";

        if(token==null|| !tokenMap.containsKey(token)){
            logger.error("[get log info failed]");
            return Result.fail(msg);

        }

        try {
            String method = json.getString("method");
            String paramsStr = json.getJSONObject("params").toJSONString();

            HashMap<String, Object> params = JsonUtil.json2obj(paramsStr
                    , HashMap.class);

            return method(method,params);

        }catch(Exception e){
            logger.error("[get log failed]");
            msg = "获取日志信息失败";
        }

        return Result.fail(msg);
    }

    /**
     * 添加日志信息
     * @param json json{...} 日志信息
     * @param request 请求
     * @return 返回日志信息
     */
    @PostMapping("/addAdminLogInfo")
    @ResponseBody
    public Result addAdminLogInfo(@RequestBody JSONObject json
            , HttpServletRequest request){
        String msg = "保存日志失败";
        String token = request.getHeader(AUTH_TOKEN);

        if(token==null|| !tokenMap.containsKey(token)){
            logger.error("[add log info failed]");
            return Result.fail(msg);
        }

        try{
            AdminLogEntity entity = JsonUtil.json2obj(json.toJSONString()
                    ,AdminLogEntity.class);

            service.addAdminLog(entity);

            return Result.success(entity);

        } catch(Exception e){
            logger.error("[save info failed]");
            msg = "添加日志失败";
        }

        return Result.fail(msg);
    }

    /**
     * 添加日志信息
     * @param json json{...} 日志信息
     * @param request 请求
     * @return 返回日志信息
     */
    @PostMapping("/modifyAdminLogInfo")
    @ResponseBody
    public Result modifyAdminLogInfo(@RequestBody JSONObject json
            , HttpServletRequest request){
        String msg = "验签失败";
        String token = request.getHeader(AUTH_TOKEN);

        if(token==null|| !tokenMap.containsKey(token)){
            logger.error("[modify log info failed]");
            return Result.fail(msg);
        }

        try{
            AdminLogEntity entity = JsonUtil.json2obj(json.toJSONString()
                    ,AdminLogEntity.class);



            service.changeAdminLog(entity);

            entity = service.getAdminLogById(entity.getLogId());

            return Result.success("操作成功",entity);

        } catch(Exception e){
            logger.error("[save info failed]");
            msg = "修改日志失败";
        }

        return Result.fail(msg);
    }

    /**
     * 删除日志信息
     * @param json ids 日志信息id数组
     * @param request 请求
     * @return 返回日志信息
     */
    @PostMapping("/deleteAdminLogInfo")
    @ResponseBody
    public Result deleteAdminLogInfo(@RequestBody JSONObject json
            , HttpServletRequest request){
        String msg = "验签失败失败";
        String token = request.getHeader(AUTH_TOKEN);

        if(token==null|| !tokenMap.containsKey(token)){
            logger.error("[delete patient info failed]");
            return Result.fail(msg);
        }

        try{

            Long[] ids = json.getObject("ids",Long[].class);
            int errorNumber = 0;

            for(Long id : ids){
                try {
                    service.deleteAdminLog(id);
                }catch(Exception e){
                    logger.error("[error in delete log]",e);
                    errorNumber ++;
                }

            }
            if(errorNumber == 0)
                return Result.success("操作成功");
            else
                msg = "共有"+errorNumber+"条日志删除失败";

        } catch(Exception e){
            logger.error("[save info failed]");
            msg = "添加日志失败";
        }

        return Result.fail(msg);
    }

    /**
     * 获取日志信息
     * @param json 日志id
     * @param request 请求
     * @return 日志信息
     */
    @PostMapping("/selectAdminLogById")
    @ResponseBody
    public Result selectPatientById(@RequestBody JSONObject json
            , HttpServletRequest request){
        String token = request.getHeader(AUTH_TOKEN);
        String msg = "验签验证失败";
        if(token==null|| !tokenMap.containsKey(token)){
            logger.error("[get patient info failed]");
            return Result.fail(msg);
        }

        try {
            Long logId = json.getLong("logId");
            AdminLogEntity log = service.getAdminLogById(logId);

            return Result.success(log);

        } catch (Exception e){
            logger.error("[failed to get log by id]",e);
            msg = "获取日志信息失败";
        }

        return Result.fail(msg);
    }



    private Result method(String method, Map<String,Object> params)
            throws Exception{
        List<AdminLogEntity> list = new ArrayList<>();

        switch(method){
            case "all":{
                list = service.getAllAdminLog();
            }
            break;
            case "all-page":{
                list = service.getAllAdminLog();

                Integer current = (Integer) params.get("current");
                Integer size = (Integer) params.get("size");
                Page<AdminLogEntity> page = new Page<>(list,size,current);
                return Result.success(page.getPageDate());
            }
            case "operator-page":{
                String id = (String) params.get("id");
                list = service.getAdminLogByOperator(Integer.valueOf(id));

                Integer current = (Integer) params.get("current");
                Integer size = (Integer) params.get("size");
                Page<AdminLogEntity> page = new Page<>(list,size,current);
                return Result.success(page.getPageDate());
            }

            default:
                logger.error("unknown method=>" + method);
                return Result.fail("未知查找方法");
        }

        return Result.success(list);
    }
}
